package com.caigp.cookbook2.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import com.caigp.cookbook2.R;
import com.caigp.cookbook2.activity.MainActivity;
import com.caigp.cookbook2.activity.SearchListActivity;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class SearchFragment extends Fragment {

    @BindView(R.id.start_search)
    LinearLayout startSearch;

    private View view;

    @BindView(R.id.hot_recycler_view)
    RecyclerView recyclerView;

    private MainActivity mainActivity;

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        mainActivity = (MainActivity) context;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_search, container, false);
        ButterKnife.bind(this, view);
        initRecyclerView();
        startSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), SearchListActivity.class);
                startActivity(intent);
            }
        });
        return view;
    }

    private void initRecyclerView() {
        List<String> hotList = mainActivity.hotList();
        GridLayoutManager glm = new GridLayoutManager(getContext(), 4);
        BaseQuickAdapter<String, BaseViewHolder> adapter = new BaseQuickAdapter<String, BaseViewHolder>(R.layout.item_menu, hotList) {
            @Override
            protected void convert(@NonNull BaseViewHolder helper, String item) {
                helper.setText(R.id.text_view, item);
            }
        };
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent(getContext(), SearchListActivity.class);
                intent.putExtra("name", hotList.get(position));
                startActivity(intent);
            }
        });
        recyclerView.setLayoutManager(glm);
        recyclerView.setAdapter(adapter);
    }
}
